import React, { useEffect, useRef } from 'react';
import { Application, Texture } from 'pixi.js';
import { Engine } from 'matter-js';
import { useGameStore } from './store/gameStore';
import { RenderEngine } from './engine/renderer/RenderEngine';
import { PhysicsEngine } from './engine/physics/PhysicsEngine';
import { GameManager } from './engine/GameManager';

const App: React.FC = () => {
  const gameCanvasRef = useRef<HTMLDivElement>(null);
  const renderEngine = useRef<RenderEngine>();
  const physicsEngine = useRef<PhysicsEngine>();
  const gameManager = useRef<GameManager>();
  const gameStore = useGameStore();

  // 初始化游戏引擎
  useEffect(() => {
    if (!gameCanvasRef.current) return;

    // 创建渲染引擎
    renderEngine.current = new RenderEngine(window.innerWidth, window.innerHeight);

    // 创建物理引擎
    physicsEngine.current = new PhysicsEngine();

    // 添加画布到DOM
    gameCanvasRef.current.appendChild(renderEngine.current.getView());

    // 创建游戏管理器
    if (renderEngine.current && physicsEngine.current) {
      gameManager.current = new GameManager(renderEngine.current, physicsEngine.current);
      
      // 初始化游戏
      gameManager.current.initGame();
      
      // 启动游戏
      gameStore.startGame();
    }

    // 窗口大小调整处理
    const handleResize = () => {
      if (!renderEngine.current) return;
      renderEngine.current.resize(window.innerWidth, window.innerHeight);
    };
    window.addEventListener('resize', handleResize);

    // 清理函数
    return () => {
      window.removeEventListener('resize', handleResize);
      gameStore.endGame();
      renderEngine.current?.destroy();
      physicsEngine.current?.destroy();
    };
  }, []);
  
  // 游戏暂停/恢复处理
  useEffect(() => {
    const handleKeyPress = (e: KeyboardEvent) => {
      if (e.code === 'Escape') {
        if (gameStore.isPaused) {
          gameStore.resumeGame();
        } else {
          gameStore.pauseGame();
        }
      }
    };
    
    window.addEventListener('keydown', handleKeyPress);
    return () => window.removeEventListener('keydown', handleKeyPress);
  }, [gameStore.isPaused]);

  return (
    <div className="game-container">
      <div ref={gameCanvasRef} className="game-canvas" />
    </div>
  );
};

export default App;